// const { query } = require("./access");
const { query } = require("./mysql/index");

const child_process = require("child_process");
const { outExcel } = require("./excle");
const fs = require("fs");
const arr = [];
let result_arr = [];
const t0 = Date.now();

function allEnd() {
  console.log(result_arr.length);
  outExcel(result_arr);
  console.log(`总耗时${(Date.now() - t0) / 1000}秒`);
}

/**
 * @description 主函数
 */
(async function () {
  const airlineList = await query(`select * from flight_airline where LineType = '国内班机航线'`);

  const evey_length = Math.ceil(airlineList.length / 4);

  for (let i = 1; i <= 4; i++) {
    arr.push(i);
    const workerProcess = child_process.fork("child_process.js", [i]);

    const child_data = airlineList.slice((i - 1) * evey_length, i * evey_length);

    workerProcess.send(child_data);

    workerProcess.on("message", (msg) => {
      result_arr.push(...msg);
    });
    workerProcess.on("error", (data) => {
      console.log(data);
    });
    workerProcess.on("exit", (code) => {
      console.log("进程已退出,退出代码 " + code);
      arr.pop();
      if (arr.length == 0) {
        allEnd();
      }
    });
  }
})();
